<?php

namespace App\Models\User;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
// 引入 JWTSubject 接口
use Illuminate\Support\Facades\Hash;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use DateTimeInterface;
class User extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable;
    use SoftDeletes;
    protected $table = 'user';
    protected $primaryKey = 'user_id';
    protected $dateFormat = 'Y-m-d H:i:s';
    protected $with = ['dept'];
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'user_name',
        'status',
        'email',
        'password',
    ];

    protected function serializeDate(DateTimeInterface $date): string
    {
        // 格式化为 年月日时分秒（如：2025-10-17 00:38:59）
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * @Notes:重写方法 JWTSubject, 获取token用
     * @return mixed
     * @author: Liao Hong
     * @Time: 2025/10/18   9:31
     * @Interface getJWTIdentifier
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @Notes:重写方法 JWTSubject, 获取token用
     * @return string[]
     * @author: Liao Hong
     * @Time: 2025/10/18   9:31
     * @Interface getJWTCustomClaims
     */
    public function getJWTCustomClaims(): array
    {
        return [
            'role' => 'user'
        ];
    }

    /**
     * @Notes:关联角色
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     * @author: Liao Hong
     * @Time: 2025/10/21   14:43
     * @Interface getRole
     */
    public function roles(): BelongsToMany
    {
        // 关联表：user_role；用户表外键：user_id；角色表外键：role_id
        return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id');
    }

    /**
     * @Notes:关联部门
     * @author: Liao Hong
     * @Time: 2025/10/21   15:09
     * @Interface dept
     */
    public function dept()
    {
        return $this->hasOne(Dept::class,'dept_id','dept_id');

    }
}
